const express = require('express');
const cors = require('cors');
const app = express();
const goodsRouter = require('./routes/goods');

// 添加请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 添加根路由
app.get('/', (req, res) => {
  res.json({ message: '服务器运行正常' });
});

// 测试数据库连接
app.get('/test-db', async (req, res) => {
  try {
    const db = require('./config/db');
    const [result] = await db.query('SELECT 1');
    res.json({ 
      message: '数据库连接成功',
      data: result 
    });
  } catch (error) {
    res.status(500).json({ 
      message: '数据库连接失败',
      error: error.message 
    });
  }
});

// API 路由
const userRouter = require('./routes/user');
app.use('/api/user', userRouter);
app.use('/api/menu', require('./routes/menu'));
app.use('/api/order', require('./routes/order'));
app.use('/api/goods', goodsRouter);
app.use('/api/test', require('./routes/test'));

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`服务器已启动: http://localhost:${PORT}`);
});